package com.syg.boot.util.net;

import com.google.common.net.InetAddresses;
import com.syg.boot.util.number.NumberMoreUtil;
import com.syg.boot.util.text.StringUtil;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

/**
 * @author syg
 * @date 2021年11月24日19:43:12
 * @version 1.0
 */
public abstract class IpUtil {

    public static int toInt(InetAddress address) {
        return InetAddresses.coerceToInteger(address);
    }

    public static String toString(InetAddress address) {
        return InetAddresses.toAddrString(address);
    }

    public static Inet4Address fromInt(int address) {
        return InetAddresses.fromInteger(address);
    }

    public static InetAddress fromIpString(String address) {
        return InetAddresses.forString(address);
    }

    public static Inet4Address fromIpv4String(String address) {
        byte[] bytes = ip4StringToBytes(address);
        if (bytes == null) {
            return null;
        } else {
            try {
                return (Inet4Address)Inet4Address.getByAddress(bytes);
            } catch (UnknownHostException var3) {
                throw new AssertionError(var3);
            }
        }
    }

    public static String intToIpv4String(int i) {
        return (new StringBuilder(15)).append(i >> 24 & 255).append('.').append(i >> 16 & 255).append('.').append(i >> 8 & 255).append('.').append(i & 255).toString();
    }

    public static int ipv4StringToInt(String ipv4Str) {
        byte[] byteAddress = ip4StringToBytes(ipv4Str);
        return byteAddress == null ? 0 : NumberMoreUtil.toInt(byteAddress);
    }

    private static byte[] ip4StringToBytes(String ipv4Str) {
        if (ipv4Str == null) {
            return null;
        } else {
            List<String> it = StringUtil.split(ipv4Str, '.', 4);
            if (it.size() != 4) {
                return null;
            } else {
                byte[] byteAddress = new byte[4];

                for(int i = 0; i < 4; ++i) {
                    int tempInt = Integer.parseInt((String)it.get(i));
                    if (tempInt > 255) {
                        return null;
                    }

                    byteAddress[i] = (byte)tempInt;
                }

                return byteAddress;
            }
        }
    }
}
